package aes

import (
	"crypto/aes"
	"crypto/cipher"

	"github.com/pkg/errors"
)

// IV 初始化向量，对数据执行加密转换
var IV = []byte(`B5I3NRGdhgeduXUj`)

// EncryptCBC 加密，使用CBC模式
// key长度必须是 16/24/32
func EncryptCBC(plainText []byte, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	plainText = paddingPKCS7(plainText, blockSize)

	if len(IV) != block.BlockSize() {
		return nil, errors.New("The length of iv must be 16")
	}

	blockMode := cipher.NewCBCEncrypter(block, IV[:blockSize])
	cipherText := make([]byte, len(plainText))
	blockMode.CryptBlocks(cipherText, plainText)

	return cipherText, nil
}

// EncryptCBC 解密，使用CBC模式
// key长度必须是 16/24/32
func DecryptCBC(cipherText []byte, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	if len(cipherText) < blockSize {
		return nil, errors.New("cipherText too short")
	}

	if len(cipherText)%blockSize != 0 {
		return nil, errors.New("cipherText is not a multiple of the block size")
	}

	if len(IV) != block.BlockSize() {
		return nil, errors.New("The length of iv must be 16")
	}

	blockModel := cipher.NewCBCDecrypter(block, IV[:blockSize])
	plainText := make([]byte, len(cipherText))
	blockModel.CryptBlocks(plainText, cipherText)

	return unPaddingPKCS7(plainText), nil
}
